package com.company.oa.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.common.exception.BusinessException;
import com.company.oa.workflow.dto.leave.LeaveDTO;
import com.company.oa.workflow.entity.leave.Leave;
import com.company.oa.workflow.mapper.LeaveMapper;
import com.company.oa.workflow.service.LeaveService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper, Leave> implements LeaveService {

    @Override
    public IPage<Leave> getPage(int page, int size, Leave leave) {
        LambdaQueryWrapper<Leave> wrapper = new LambdaQueryWrapper<>();
        if (leave != null) {
            if (StringUtils.hasText(leave.getTitle())) {
                wrapper.like(Leave::getTitle, leave.getTitle());
            }
            if (leave.getType() != null) {
                wrapper.eq(Leave::getType, leave.getType());
            }
            if (leave.getStatus() != null) {
                wrapper.eq(Leave::getStatus, leave.getStatus());
            }
        }
        wrapper.orderByDesc(Leave::getCreateTime);
        return page(new Page<>(page, size), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createLeave(LeaveDTO leaveDTO, Long userId) {
        Leave leave = new Leave();
        BeanUtils.copyProperties(leaveDTO, leave);
        leave.setApplicantId(userId);
        leave.setStatus(0); // 设置为草稿状态
        leave.setCreateTime(LocalDateTime.now());
        leave.setUpdateTime(LocalDateTime.now());
        return save(leave);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLeave(LeaveDTO leaveDTO) {
        Leave leave = getById(leaveDTO.getId());
        if (leave == null) {
            throw new BusinessException("请假申请不存在");
        }
        if (leave.getStatus() != 0) {
            throw new BusinessException("只能修改草稿状态的请假申请");
        }
        BeanUtils.copyProperties(leaveDTO, leave);
        leave.setUpdateTime(LocalDateTime.now());
        return updateById(leave);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submitLeave(Long id) {
        Leave leave = getById(id);
        if (leave == null) {
            throw new BusinessException("请假申请不存在");
        }
        if (leave.getStatus() != 0) {
            throw new BusinessException("只能提交草稿状态的请假申请");
        }
        leave.setStatus(1); // 设置为待审批状态
        leave.setSubmitTime(LocalDateTime.now());
        leave.setUpdateTime(LocalDateTime.now());
        return updateById(leave);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelLeave(Long id) {
        Leave leave = getById(id);
        if (leave == null) {
            throw new BusinessException("请假申请不存在");
        }
        if (leave.getStatus() != 0 && leave.getStatus() != 1) {
            throw new BusinessException("只能取消草稿或待审批状态的请假申请");
        }
        leave.setStatus(4); // 设置为已取消状态
        leave.setUpdateTime(LocalDateTime.now());
        return updateById(leave);
    }

    @Override
    public String uploadAttachment(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + fileExtension;
        String uploadPath = "uploads/leave/";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        try {
            file.transferTo(new File(uploadPath + newFilename));
            return uploadPath + newFilename;
        } catch (IOException e) {
            throw new BusinessException("文件上传失败");
        }
    }

    @Override
    public Map<String, Object> getLeaveDetail(Long id) {
        Leave leave = getById(id);
        if (leave == null) {
            throw new BusinessException("请假申请不存在");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("leave", leave);
        // 这里可以添加其他相关信息，如审批记录等
        return result;
    }

    @Override
    public IPage<Leave> getMyLeaves(int page, int size, Long userId, Integer status) {
        LambdaQueryWrapper<Leave> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Leave::getApplicantId, userId);
        if (status != null) {
            wrapper.eq(Leave::getStatus, status);
        }
        wrapper.orderByDesc(Leave::getCreateTime);
        return page(new Page<>(page, size), wrapper);
    }
}